package app.model.proxy 
{
	import app.facade.App;
	import app.model.vo.TransactionVO;
	import app.view.component.moment.Module;
	import app.view.component.moment.ModuleCore;
	import com.adobe.serialization.json.JSON;
	import com.adobe.serialization.json.JSONDecoder;
	import com.hutra.utils.Syner;
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import org.osflash.thunderbolt.Logger;
	/**
	 * ...
	 * @author hungconcon
	 */
	public class UtilityProxy extends ModuleCore
	{
		/**
		 * Always default exists to determine the object reference
		 */
		public static const NAME:String = "UtilityProxy";	
		
		/**
		 * The data received from the load operation. This property
		 * is populated only when the load operation is complete.
		 * The format of the data depends on the setting of the
		 * dataFormat property: dataFormat property is URLLoaderDataFormat.TEXT
		 */
		private var data:Object;
		
		/**
		 * transaction is a block transfer of data censorship 
		 * come back to this place agents in the transaction request action
		 */
		private var transaction:TransactionVO;
		
		/**
		 * The command of the facade, accessible as App.COMMAND...
		 * It can be used to transfer data back block has been sent , through which , 
		 * the registration is imperative to be able to get back to the desired data
		 */
		private var command:String = '';
		
		/**
		 * The object of desire when you receive data
		 */
		private var synchronize:*;
		
		/**
		 * Creates a URLLoader object.
		 * @param	request	A URLRequest object specifying
		 *   the URL to download.  If this parameter is omitted,
		 *   no load operation begins.  If
		 *   specified, the load operation begins
		 *   immediately (see the load entry for more information).		
		 */
		private var loader:URLLoader;
		
		/**
		 * Creates a UtilityProxy object.
		 */
		public function UtilityProxy() { 
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, completeHandler);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		/**
		 * Sends and loads data from the specified URL. The data can be received as
		 * text, raw binary data, or URL-encoded variables, depending on the
		 * value you set for the dataFormat property. Note that
		 * the default value of the dataFormat property is text.
		 * If you want to send data to the specified URL, you can set the data
		 * property in the URLRequest object.
		 * 
		 * @param	cmd as an application facade
		 * @param	url	as link
		 * @param	variable as object "?id=1&data=12&cmd=get"
		 * @param	block as transaction tipe
		 */
		public function load(cmd:String, url:String, variable:URLVariables = null, trans:TransactionVO = null, syn:*= null):void {
			//[0]
			command 	= cmd;
			synchronize = syn;
			transaction = trans;
			
			//[2]	
            var request:URLRequest = new URLRequest();
			//[3]
			if (variable != null){
				if (variable.tcode != undefined)
					delete variable.tcode;
				
				//@test
				//variable.sec = Math.random();
				request.url = url + variable.cmd;
				request.data = new URLVariables();
				request.method = URLRequestMethod.GET;
			}
			//[4]
            try { 
				loader.load(request); 
			} catch (error:Error) { 
				sendNotification(App.SHOW_ERROR,{value:"UtilityProxy.load: Unable to load requested document."});
			}
        }
		
		/**
		 * Implementation of successful transactions.
		 * [0] Data empty when we get it from server
		 * [1] if the transaction is returned to the method of implementation of interactive objects , assign the value to data roll
		 * [2] sending it from the proxy statement outside the facade get hold by Module
		 * @param	event as urlloader target
		 */
		private function completeHandler(event:Event):void {
			var dataReceive:TransactionVO;
			var dataSynchronize:*;
			//[0]
            var loader:URLLoader = URLLoader(event.target);
			
			if (loader.data == '') {
				sendNotification(App.SHOW_ERROR, { value:"ConnectProxy.completeHandler: Data empty" } );
				return;
			}
			//[0.1]
			var newopp:*;
			try 
			{
				newopp = new JSONDecoder( loader.data, true ).getValue(); //JSON.parse(loader.data);
			}catch (ex:Error) {
				sendNotification(App.SHOW_ERROR, { value:"ConnectProxy.completeHandler: JSON decode error" } );
				return;
			}
			//[0.2]
			if (synchronize != null) {
				dataSynchronize = Syner.synchronizeValueObject(synchronize, newopp);
			}else {
				dataSynchronize = newopp;
			}
			//[1]
			//dataReceive = (transaction == null)?dataSynchronize: { roll:transaction, data:dataSynchronize };
			transaction.data = dataSynchronize;
			//[2]
			sendNotification(command, transaction);
        }
		
		/**
		 * Creates an Event object that contains information about security error events.
		 * Event objects are passed as parameters to event listeners.
		 * @param	event
		 */
        private function securityErrorHandler(event:SecurityErrorEvent):void {
			sendNotification(App.SHOW_ERROR,{value:"ConnectProxy.securityErrorHandler"});
		}
		
		/**
		 * Creates an Event object that contains specific information about ioError events.
		 * Event objects are passed as parameters to Event listeners.
		 * @param	event
		 */
        private function ioErrorHandler(event:IOErrorEvent):void { 
			sendNotification(App.SHOW_ERROR,{value:"ConnectProxy.ioErrorHandler"});
		}
		
	}
}